package com.simple.space.modules.base.controller;

import com.github.pagehelper.PageInfo;
import com.simple.space.common.constant.Result;
import com.simple.space.util.WebUtil;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * <br/>
 * 基础控制层接口
 * </p>
 */

public class BaseController {

	protected Result response(Integer code, String message, Object data) {
		return new Result(code, message, data);
	}

	protected Result response(Integer code, String message) {
		return new Result(code, message);
	}

	protected Map<String, Object> parseToRows(PageInfo pageInfo) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("rows", pageInfo.getList());
		map.put("total", pageInfo.getTotal());
		return map;
	}

	protected ModelAndView getModelAndView(String path) {
		return new ModelAndView(path);
	}

	protected ModelAndView redirect(String path) {
		return getModelAndView("redirect:" + path);
	}

	protected ModelAndView redirect(String path, String objName, Object obj) {
		return redirect(path).addObject(objName, obj);
	}

	protected void download(String path, HttpServletResponse response) {
		String fileName = WebUtil.getFileName(path);
		fileName = fileName.substring(1);
		response.setContentType("application/octet-stream; charset=utf-8");
		response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
		byte[] buff = new byte[10240];
		BufferedInputStream bis = null;
		OutputStream os;
		try {
			os = response.getOutputStream();
			bis = new BufferedInputStream(new FileInputStream(new File(path)));
			int i = bis.read(buff);
			while (i != -1) {
				os.write(buff, 0, buff.length);
				os.flush();
				i = bis.read(buff);
			}
		} catch (IOException e) {
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
				}
			}
		}
	}

	protected ResponseEntity<InputStreamResource> downloadFile(String filePath) throws IOException {
		FileSystemResource file = new FileSystemResource(filePath);
		HttpHeaders headers = new HttpHeaders();
		headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
		headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getFilename()));
		headers.add("Pragma", "no-cache");
		headers.add("Expires", "0");

		return ResponseEntity.ok().headers(headers).contentLength(file.contentLength()).contentType(
				MediaType.parseMediaType("application/octet-stream")).body(
						new InputStreamResource(file.getInputStream()));
	}
}
